package com.bank.utils;

import java.sql.*;
import java.util.List;

//对数据库的初始化
public class DbUtils {
    //characterEncoding=utf8
    private static final String url = "jdbc:mysql://localhost:3306/test2?useSSL=false&serverTimezone=UTC";
    private static final String username = "root";
    private static final String password = "050602";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection open() {
        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //从db中获取内容存入集合中
    public static PreparedStatement preparedStatement(String sql, List param, Connection connection) {
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.size(); i++) {
                    statement.setObject(i + 1, param.get(i));
                }
            }
            return statement;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        try {
            if (resultSet != null)
                resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static int executeUpdate(String sql, List param) {
        PreparedStatement statement = null;
        Connection connection = null;
        try {
            connection = DbUtils.open();
            statement = DbUtils.preparedStatement(sql, param, connection);
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeAll(connection, statement, null);
        }
        return 0;
    }
}
